﻿using IdentityServer.Domain.IRepositories;
using IdentityServer.Domain.IServices;
using IdentityServer.Infrastructure.Options;
using System.Net;
using System.Net.Mail;

namespace IdentityServer.Infrastructure.Services
{
    public class QQEmailClient : IEmailClient
    {
        private readonly IEmailRepository emailRepository;
        public IEmailRepository EmailRepository { get { return emailRepository; } }

        public QQEmailClient(IEmailRepository emailRepository)
        {
            this.emailRepository = emailRepository;
        }

        public async Task<bool> SendEmail(string email,string code, string subject, string body)
        {
            if(await emailRepository.UpdateEmailSenderAsync(email, code))
            {
                return Sender(email, subject, body);
            }
            else
            {
                return false;
            }
        }

        public bool Sender(string email, string subject, string body)
        {
            QQEmailOptions options = new QQEmailOptions
            {
                SendEmail = "tianchuansoft@foxmail.com",
                SmtpService = "smtp.qq.com",
                Sendpwd = Environment.GetEnvironmentVariable("Sendpwd")
            };

            //确定smtp服务器地址 实例化一个Smtp客户端
            SmtpClient smtpclient = new SmtpClient();
            smtpclient.Host = options.SmtpService;

            //确定发件地址与收件地址
            MailAddress sendAddress = new MailAddress(options.SendEmail);
            MailAddress receiveAddress = new MailAddress(email);

            //构造一个Email的Message对象 内容信息
            MailMessage mailMessage = new MailMessage(sendAddress, receiveAddress);
            mailMessage.Subject = subject;
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
            mailMessage.Body = body;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;

            //邮件发送方式  通过网络发送到smtp服务器
            smtpclient.DeliveryMethod = SmtpDeliveryMethod.Network;
            //如果服务器支持安全连接，则将安全连接设为true
            smtpclient.EnableSsl = true;
            try
            {
                //是否使用默认凭据，若为false，则使用自定义的证书，就是下面的networkCredential实例对象
                smtpclient.UseDefaultCredentials = false;

                //指定邮箱账号和密码,需要注意的是，这个密码是你在QQ邮箱设置里开启服务的时候给你的那个授权码
                NetworkCredential networkCredential = new NetworkCredential(options.SendEmail, options.Sendpwd);
                smtpclient.Credentials = networkCredential;

                //发送邮件
                smtpclient.Send(mailMessage);
                return true;

            }
            catch (System.Net.Mail.SmtpException ex) { return false; }
        }
    }
}
